import os
import subprocess

import psycopg2
import requests
import pyodbc

import dm7py
from dm7py import connect
def getArcGISTableNames(url):
    """

    Args:
        url: arcgis服务的地址 http://192.168.211.92:6080/arcgis/rest/services/wuhan/MapServer

    Returns: 返回发布图层的图层名称列表

    """
    infoUrl = url + "?f=json"
    serviceInfoJson = requests.get(infoUrl).json()
    layers = serviceInfoJson.get("layers")
    layer_names = []
    for layer in layers:
        layer_names.append(layer.get("name"))
    return layer_names


def convert2Shp(dm_bin_dir, save_dir, scheme, table_name):
    """

    Args:
        dm_bin_dir: dm安装路径下的bin文件
        save_dir: 文件保存路径
        scheme: 达梦存放空间数据的模式
        table_name:表名

    Returns:

    """
    save_path = os.path.join(save_dir, table_name)
    cmd_str = dm_bin_dir + '\dmst2shp.exe SYSDBA/egovaegova@127.0.0.1:5236 shapefile={0} sql=\"select * from {1}.{2}" auto_overwrite=1'
    cmd_str = cmd_str.format(save_path, scheme, table_name)
    result = subprocess.run(cmd_str, shell=True, capture_output=True, text=True)
    print(result)


def batchConvert(layer_names, dm_bin_dir, save_dir, scheme):
    for layer_name in layer_names:
        convert2Shp(dm_bin_dir, save_dir, scheme, layer_name)


def create_pg_table_by_dm():
    pg_con = psycopg2.connect(database="beijing", user="postgres", password="postgres", host="192.168.211.87", port="5432")
    dama_conn = pyodbc.connect('DRIVER={DM8 ODBC DRIVER};Server=127.0.0.1;Database=<dama_database_name>;UID=SYSDBA;PWD=egovaegova')

if __name__ == '__main__':
    layer_names = getArcGISTableNames(r"http://192.168.211.92:6080/arcgis/rest/services/%E6%AD%A6%E6%B1%89%E7%9F%A2%E9%87%8F/MapServer")
    batchConvert(layer_names, r"D:\software\professional\dmdbms\bin", "test")